package widget.bar;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.Window;

import java.lang.ref.WeakReference;

/**
 * Created by Mr.Fan on 2016/11/11.
 */

public class SystemBar {
    public static int BASE_COLOR = Color.BLACK;

    private StatusBar mStatusBar;
    private NavigationBar mNavigationBar;

    private int mMainColor = BASE_COLOR;
    private WeakReference<View> refContentView;


    public static SystemBar obtain() {
        return new SystemBar();
    }

    public synchronized StatusBar statusBar() {
        if (mStatusBar == null)
            mStatusBar = new StatusBar(this);
        return mStatusBar;
    }

    public synchronized NavigationBar navigationBar() {
        if (mNavigationBar == null)
            mNavigationBar = new NavigationBar(this);
        return mNavigationBar;
    }

    /**
     * for multi view ( DrawerLayout...);
     *
     * @param contentView
     * @return
     */
    public SystemBar setContentViewForMultiLayout(View contentView) {
        this.refContentView = new WeakReference<>(contentView);
        return this;
    }

    protected View getContentView() {
        return refContentView != null ? refContentView.get() : null;
    }

    public void setMainColor(int color) {
        this.mMainColor = color;
    }

    protected int getMainColor() {
        return this.mMainColor;
    }

    public boolean apply(@NonNull Activity activity) {
        if (activity != null)
            return apply(activity.getWindow());
        return false;
    }

    public boolean apply(@NonNull Window window) {
        if (window == null)
            return false;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return false;
        }
        if (!window.isActive())
            return commit(window);
        else {
            Runner runner = new Runner(window, this);
            window.getDecorView().post(runner);
        }
        return true;
    }

    private boolean commit(@NonNull Window window) {
        if (mStatusBar != null) {
            mStatusBar.commit(window);
        }
        if (mNavigationBar != null)
            mNavigationBar.commit(window);
        return true;
    }

    private static final class Runner implements Runnable {
        private WeakReference<Window> reference;
        private SystemBar systemBar;

        public Runner(Window window, SystemBar systemBar) {
            this.reference = new WeakReference<>(window);
            this.systemBar = systemBar;
        }

        @Override
        public void run() {
            Window window = reference != null ? reference.get() : null;
            if (window != null && systemBar != null) {
                systemBar.commit(window);
            }

        }
    }
}
